package com.zhongshengnetwork.rightbe.my.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
//import android.support.annotation.RequiresApi;
//import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.wang.avi.AVLoadingIndicatorView;
import com.wangnan.library.GestureLockView;
import com.wangnan.library.listener.OnGestureLockListener;
import com.wangnan.library.model.Point;
import com.wangnan.library.painter.AliPayPainter;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.BuildConfig;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.Constant.LetterConstant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.angentweb.WebActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.download.ApkUpdateUtils;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbservice.LogindbService;
import com.zhongshengnetwork.rightbe.gsonmodel.ApkModel;
import com.zhongshengnetwork.rightbe.gsonmodel.BindInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.login.BDThirdActivity;
import com.zhongshengnetwork.rightbe.login.VerifyActivity;
import com.zhongshengnetwork.rightbe.my.model.DownLoadManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.zhongshengnetwork.rightbe.MainActivity.REQUEST_PERMISSION;

//三检查OK:2016-11-30
public class SettingsActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private static final int Register_Request = 10000;
    private static final int Verify_Request = 10001;
    private List<String> list=null;
    private List<String> groupkey=new ArrayList<String>();
    private ListView listview;
    private TopBarView topbar;
    private String version;
    private final int UPDATA_NONEED = 0;
    private final int UPDATA_CLIENT = 1;
    private final int GET_UNDATAINFO_ERROR = 2;
    private final int SDCARD_NOMOUNTED = 3;
    private final int DOWN_ERROR = 4;
    private final int DOWN_OK = 5;
    private ApkModel apkModel;
    private LinearLayout mLinearLayout;
    private AVLoadingIndicatorView avi;
    private BindInfoModel bindInfoModel = null;
    private MyAdapter adapter;
    private File apkFile = null;
    private boolean isLogout = false;
    private boolean isNotify = false;
    private boolean offAccountState = false;
    private String oldMobile = "";

    //以下是qq相关
    private static final String APP_ID = "1105905402";//官方获取的APPID
    private Tencent mTencent;
    private BaseUiListener mIUiListener;
    private UserInfo mUserInfo;

    private FrameLayout gesture_layout;
    private GestureLockView mGuestureLockView;
    private TextView glv_title;
    private TextView glv_tip;
    private String gestureKey = "";
    private String oldGestureKey = "";

    class NiCaiFu360Painter extends AliPayPainter {
        @Override
        public void drawNormalPoint(Point point, Canvas canvas, Paint normalPaint) {
            super.drawNormalPoint(point, canvas, normalPaint);
        }

        @Override
        public void drawPressPoint(Point point, Canvas canvas, Paint pressPaint) {
            //1.绘制中心点
            pressPaint.setStyle(Paint.Style.FILL);
            canvas.drawCircle(point.x,point.y,point.radius/4.0f, pressPaint);
            //2.绘制边界圆
            pressPaint.setStyle(Paint.Style.STROKE);
            pressPaint.setStrokeWidth(6);
            canvas.drawCircle(point.x, point.y, getGestureLockView().getRadius(), pressPaint);
            //super.drawPressPoint(point, canvas, pressPaint);
        }

        @Override
        public void drawErrorPoint(Point point, Canvas canvas, Paint errorPaint) {
            //1，绘制中心点
            errorPaint.setStyle(Paint.Style.FILL);
            canvas.drawCircle(point.x, point.y, point.radius/4.0f, errorPaint);
            //2，绘制边界圆
            errorPaint.setStyle(Paint.Style.STROKE);
            errorPaint.setStrokeWidth(6);
            canvas.drawCircle(point.x, point.y, getGestureLockView().getRadius(), errorPaint);
            //super.drawErrorPoint(point, canvas, errorPaint);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        registerBoradcastReceiver();
        setSwipeBackEnable(false);
        mLinearLayout = (LinearLayout) findViewById(R.id.container);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);

        oldGestureKey = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(LetterConstant.GestureKey+CustomApplication.loginModel.getUid(), "");
        gesture_layout = (FrameLayout) findViewById(R.id.gesture_layout);
        gesture_layout.setBackgroundColor(AppThemeUtils.getInstance().getThemeColor());
        glv_title = (TextView) findViewById(R.id.glv_title);
        if (CommonUtils.isEmpty(oldGestureKey)){
            glv_title.setText("设置手势");
        }else {
            glv_title.setText("取消手势");
        }
        glv_tip = (TextView) findViewById(R.id.glv_tip);
        glv_tip.setClickable(true);
        glv_tip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gesture_layout.setVisibility(View.INVISIBLE);
            }
        });
        mGuestureLockView = (GestureLockView) findViewById(R.id.glv);
        mGuestureLockView.setPainter(new NiCaiFu360Painter());
        mGuestureLockView.setGestureLockListener(new OnGestureLockListener() {
            @Override
            public void onStarted() {

            }

            @Override
            public void onProgress(String progress) {

            }

            @Override
            public void onComplete(String result) {
                Log.e("TAG","密码是："+result);

                if (CommonUtils.isEmpty(result)){
                    return;
                }else{
                    if (CommonUtils.isEmpty(oldGestureKey)){//设置手势
                        if (CommonUtils.isEmpty(gestureKey)){
                            mGuestureLockView.clearView();
                            gestureKey = result;
                            glv_title.setText("再次确认手势");
                        }else {
                            if (gestureKey.equals(result)){
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(LetterConstant.GestureKey+CustomApplication.loginModel.getUid(), result);
                                gesture_layout.setVisibility(View.INVISIBLE);
                                adapter.notifyDataSetChanged();
                            }else {
                                glv_title.setText("设置手势");
                                gestureKey = "";
                                mGuestureLockView.showErrorStatus(600);
                                mGuestureLockView.clearView();
                                ToastUtil.show(SettingsActivity.this, "两次输入的手势不一致，请重新设置");
                            }
                        }
                    }else {//取消手势
                        if (oldGestureKey.equals(result)){
                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(LetterConstant.GestureKey+CustomApplication.loginModel.getUid(), "");
                            gesture_layout.setVisibility(View.INVISIBLE);
                            mGuestureLockView.clearView();
                            adapter.notifyDataSetChanged();
                        }else {
                            mGuestureLockView.showErrorStatus(600);
                        }
                    }
                }
            }
        });

        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);
        isNotify =  SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.NewMsgTipKey, true);
        version = getVersionName();
        listview=(ListView) findViewById(R.id.settings_listview);
        listview.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        listview.setDivider(new ColorDrawable(AppThemeUtils.getInstance().getBackgroundColor()));
        listview.setDividerHeight(ScreenUtils.dip2px(SettingsActivity.this, 1));

        RelativeLayout settings_layout = (RelativeLayout) findViewById(R.id.settings_layout);
        settings_layout.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        initData();
        adapter=new MyAdapter();
        listview.setAdapter(adapter);
        //初始化qq主操作对象
        Tencent.setIsPermissionGranted(true);//必须调研这个再调用其他接口
        mTencent = Tencent.createInstance("1105905402", SettingsActivity.this,"com.zhongshengnetwork.rightbe.fileprovider");
        getbindInfo();
        getPushState();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
        if (mTencent != null) {
            //注销登录
            mTencent.logout(SettingsActivity.this);
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    public void initData(){

        list = new ArrayList<String>();

        groupkey.add("0组");
        List<String> aList = new ArrayList<String>();
        aList.add("接收消息推送");
        aList.add("个性推荐");
        aList.add("手势进入设置");
        aList.add("夜间模式");
        aList.add("动态评论墙");
        aList.add("界面模式");
        aList.add("设置字体大小");
        list.add("0组");
        list.addAll(aList);

        groupkey.add("A组");
        aList = new ArrayList<String>();
        aList.add("绑定手机");
        aList.add("绑定微信");
        aList.add("绑定QQ");
        list.add("A组");
        list.addAll(aList);

        groupkey.add("B组");
        List<String> bList = new ArrayList<String>();
        //bList.add("帮助中心");
        bList.add("意见反馈");
        //bList.add("关于我们");
        bList.add("用户协议");
        bList.add("隐私政策");
        bList.add("关于微句");
        bList.add("App备案号:粤ICP备2023006619号-2A");
        bList.add("申请注销账号");
        version = getVersionName();
        bList.add("检查版本 "+version);
        list.add("B组");
        list.addAll(bList);
        groupkey.add("C组");
        List<String> cList = new ArrayList<String>();
        cList.add("退出登录");
        list.add("C组");
        list.addAll(cList);
    }

    private class MyAdapter extends BaseAdapter implements View.OnClickListener {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            if(groupkey.contains(getItem(position))){
                return false;
            }
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View view=convertView;
            if(groupkey.contains(getItem(position))){
                view= LayoutInflater.from(CustomApplication.mContext).inflate(R.layout.my_list_heaer, null);
                TextView text = (TextView) view.findViewById(R.id.my_list_header_text);
                text.setText("");
                LinearLayout my_list_header_line = (LinearLayout) view.findViewById(R.id.my_list_header_line);
                my_list_header_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
            }else{
                view=LayoutInflater.from(CustomApplication.mContext).inflate(R.layout.settings_list_item, null);
                RelativeLayout settings_item = (RelativeLayout) view.findViewById(R.id.settings_item);
                settings_item.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
                String t = (String) getItem(position);
                TextView text=(TextView) view.findViewById(R.id.settings_list_text);
                text.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
                TextView logout = (TextView) view.findViewById(R.id.settings_list_logout);
                logout.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
                ImageView icon = (ImageView) view.findViewById(R.id.settings_list_icon);
                if (t.equals("退出登录")){
                    text.setVisibility(View.INVISIBLE);
                    icon.setVisibility(View.INVISIBLE);
                    logout.setVisibility(View.VISIBLE);
                    logout.setText((CharSequence) getItem(position));
                    logout.setTag(position);
                    logout.setOnClickListener(this);
                }else {
                    text.setVisibility(View.VISIBLE);
                    icon.setVisibility(View.VISIBLE);
                    logout.setVisibility(View.INVISIBLE);
                    text.setText((CharSequence) getItem(position));
                    if (position == 18){
                        text.setText((CharSequence)getItem(position));
                    }else if (position == 1){
                        //接收新消息通知
                        if (isNotify == true){
                            text.setText(getItem(position)+"（已开启）");
                        }else {
                            text.setText(getItem(position)+"（已关闭）");
                        }
                    }else if(position == 2){//个性推荐
                        if (bindInfoModel == null || CommonUtils.isEmpty(bindInfoModel.getPersonalized()) || bindInfoModel.getPersonalized().equals("1")){
                            text.setText(getItem(position)+"（已开启）");
                        }else {
                            text.setText(getItem(position)+"（已关闭）");
                        }
                    }else if(position == 3){
                        //手势进入设置
                        String key = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(LetterConstant.GestureKey+CustomApplication.loginModel.getUid(),"");
                        if (CommonUtils.isEmpty(key)){
                            text.setText(getItem(position)+"（已关闭）");
                        }else {
                            text.setText(getItem(position)+"（已开启）");
                        }
                    }else if(position == 4){
                        int appTheme = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AppThemeUtils.AppThemeKey, AppThemeUtils.AppThemeConstant.NORMAL_APP_Theme);
                        if (appTheme == AppThemeUtils.AppThemeConstant.NIGHT_APP_Theme){
                            text.setText(getItem(position)+"（已开启）");
                        }else {
                            text.setText(getItem(position)+"（已关闭）");
                        }
                    }else if(position == 5){
                        boolean isOpen = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.MoveCommentKey, true);
                        if (isOpen == true){
                            text.setText(getItem(position)+"（已开启）");
                        }else {
                            text.setText(getItem(position)+"（已关闭）");
                        }
                    }else if(position == 6){
                        if (CommonUtils.getUIMode() == AdvertUtils.UI_Simple_Mode){
                            text.setText(getItem(position)+"（个性模式）");
                        }else {
                            text.setText(getItem(position)+"（标准模式）");
                        }
                    }else if(position == 7){
                        text.setText(getItem(position)+"");
                    } else if (position == 9){
                        if (bindInfoModel != null && !CommonUtils.isEmpty(bindInfoModel.getMobile())){
                           String txt = getItem(position)+" ("+bindInfoModel.getMobile()+")";
                            text.setText(txt);
                        }
                    }else if (position == 10){
                        if (bindInfoModel != null && bindInfoModel.getWx().equals("1")){
                            String txt = getItem(position)+" (已绑定)";
                            text.setText(txt);
                        }
                    }else if (position == 11){
                        if (bindInfoModel != null && bindInfoModel.getQq().equals("1")){
                            String txt = getItem(position)+" (已绑定)";
                            text.setText(txt);
                        }
                    }
                    text.setTag(position);
                    text.setOnClickListener(this);
                }

            }
            return view;
        }

        // 监听事件实现
        public void onClick(View v) {
            int destination = (Integer) v.getTag();
            System.out.print("onClick:"+destination+"\n");
            //startActivity(new Intent(CustomApplication.mContext, LoginActivity.class));

            switch (destination) {
                case 0:
                    System.out.print("onClick:0\n");
                    break;
                case 1:
                    //接收新消息通知
                    isNotify = !isNotify;
                    adapter.notifyDataSetChanged();
                    setPushState(isNotify);
                    break;
                case 2://个性推荐
                    setPersonalized();
                    break;
                case 3:
                    //手势进入设置
                    if (bindInfoModel != null && CommonUtils.isEmpty(bindInfoModel.getMobile())){
                        bindMobile();
                    }else {
                        if (bindInfoModel != null){
                            oldGestureKey = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(LetterConstant.GestureKey+CustomApplication.loginModel.getUid(), "");
                            gestureKey = "";
                            if (CommonUtils.isEmpty(oldGestureKey)){
                                glv_title.setText("设置手势");
                            }else {
                                glv_title.setText("取消手势");
                            }
                            mGuestureLockView.clearView();
                            gesture_layout.setVisibility(View.VISIBLE);
                        }
                    }
                    break;
                case 4:
                    //夜间模式
                    showMode();
                    break;
                case 5://动态评论墙
                    showMoveComment();
                    break;
                case 6:
                    //界面模式
                    showUIMode();
                    break;
                case 7:
                    Intent fontIntent = new Intent(SettingsActivity.this, FontSizeActivity.class);
                    startActivity(fontIntent);
                    break;

                case 9://绑定手机
                    if (bindInfoModel != null && CommonUtils.isEmpty(bindInfoModel.getMobile())){
                        bindMobile();
                    }else {
                        changeMobile();
                    }
                    break;

                case 10://绑定微信
                    if (bindInfoModel != null && bindInfoModel.getWx().equals("0")){
                        wxLogin();
                    }else {
                        showUnBind("0");
                    }
                    break;
                case 11://绑定QQ
                    if (bindInfoModel != null && bindInfoModel.getQq().equals("0")){
                        avi.show();
                        //通过这句代码，SDK实现了QQ的登录，这个方法有三个参数，第一个参数是context上下文，第二个参数SCOPO 是一个String类型的字符串，表示一些权限
//                 官方文档中的说明：应用需要获得哪些API的权限，由“，”分隔。例如：SCOPE = “get_user_info,add_t”；所有权限用“all”
//                 第三个参数，是一个事件监听器，IUiListener接口的实例，这里用的是该接口的实现类
                        mIUiListener = new BaseUiListener();
                        //all表示获取所有权限
                        mTencent.login(SettingsActivity.this,"all", mIUiListener);
                    }else {
                        showUnBind("1");
                    }
                    break;
                case 13://意见反馈
                    startActivity(new Intent(SettingsActivity.this, FeedBackActivity.class));//意见反馈
                    break;
                case 14://用户协议
                    Intent webIntent = new Intent(SettingsActivity.this, MyWebActivity.class);
                    webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuagreement.do");
                    startActivity(webIntent);//用户协议
                    break;
                case 15://隐私政策
                    Intent pIntent = new Intent(SettingsActivity.this, MyWebActivity.class);
                    pIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuprivacy.do");
                    startActivity(pIntent);//用户协议
                    break;
                case 16://关于微句
                    Intent wIntent = new Intent(SettingsActivity.this, MyWebActivity.class);
                    wIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/note.do");
                    startActivity(wIntent);
                    break;
                case 17://App备案
                    Intent bIntent = new Intent(SettingsActivity.this, MyWebActivity.class);
                    bIntent.putExtra(APIKey.urlKey, "https://beian.miit.gov.cn/");
                    startActivity(bIntent);
                    break;
                case 18://申请注销账号
                    showOffAccount();
//                    Intent cIntent = new Intent(SettingsActivity.this, MyWebActivity.class);
//                    cIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/cancel.do");
//                    cIntent.putExtra("isCancel",true);
//                    startActivity(cIntent);
                    break;
                case 19://检查版本
                    getUpdate();//检查版本
                    break;
                case 21://退出登录
                    logout();
                    break;
                default:
                    break;
            }

        }
    }

    private void showMoveComment(){

        //夜间模式
        String content = "";
        String tip = "";
        String open = "";
        boolean isOpen = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.MoveCommentKey, true);
        if (isOpen == true){
            isOpen = false;
            content = "亲，应用当前已经开启动态评论墙，是否要关闭？\n（温馨提示：在评论墙所在页面，长按屏幕可以开启或者关闭动态评论墙哦）";
            tip = "动态评论墙已关闭";
            open = "关闭";
        }else {
            isOpen = true;
            content = "亲，应用当前已经关闭动态评论墙，是否要开启？\n（温馨提示：在评论墙所在页面，长按屏幕可以开启或者关闭动态评论墙哦）";
            tip = "动态评论墙已开启";
            open = "开启";
        }
        final boolean openState = isOpen;
        final String tipStr = tip;
        final String openStr = open;
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(SettingsActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage(content);
        builder.setPositiveButton(openStr, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.MoveCommentKey, openState);
                adapter.notifyDataSetChanged();
                ToastUtil.show(SettingsActivity.this,tipStr);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void showOffAccount(){
        String title = "";
        String content = "";
        String action = "";
        if (offAccountState == true){
            title = "确认注销账号";
            content = "1，账号注销后，账号所有相关发布的内容都会被系统删除，且无法恢复。\n\n" +
                    "2，账号注销后，原来绑定的手机号、QQ、微信等，都将无法再次用来进行微句的注册和登录操作。";
            action = "确认注销";
        }else {
            title = "申请注销账号";
            content = "1，账号注销后，账号所有相关发布的内容都会被系统删除，且无法恢复。\n\n" +
                    "2，账号注销后，原来绑定的手机号、QQ、微信等，都将无法再次用来进行微句的注册和登录操作。";
            action = "申请注销";
        }
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(SettingsActivity.this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(action, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (offAccountState == true){
                    userOff();
                }else {
                    offAccountState = true;
                    showOffAccount();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                offAccountState = false;
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void showMode(){

        //夜间模式
        String content = "";
        int appTheme = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AppThemeUtils.AppThemeKey, AppThemeUtils.AppThemeConstant.NORMAL_APP_Theme);
        if (appTheme == AppThemeUtils.AppThemeConstant.NIGHT_APP_Theme){
            appTheme = AppThemeUtils.AppThemeConstant.NORMAL_APP_Theme;
            content = "亲，应用当前已经开启夜间模式，如需关闭请按确定。";
        }else {
            appTheme = AppThemeUtils.AppThemeConstant.NIGHT_APP_Theme;
            content = "亲，应用当前已经关闭夜间模式，如需开启请按确定。";
        }
        final int nowAppTheme = appTheme;
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(SettingsActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage(content);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AppThemeUtils.AppThemeKey, nowAppTheme);
                AppThemeUtils.getInstance().setAppTheme(nowAppTheme);
                //重启
                restartApplication();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void showUIMode(){

        String content = "";
        int uimode = CommonUtils.getUIMode();
        if (uimode == AdvertUtils.UI_Simple_Mode){
            uimode = AdvertUtils.UI_Normal_Mode;
            content = "亲，应用当前界面使用的是个性模式，如需切换到标准模式请按确定。";
        }else {
            uimode = AdvertUtils.UI_Simple_Mode;
            content = "亲，应用当前界面使用的是标准模式，如需切换到个性模式请按确定。";
        }
        final int nowAppTheme = uimode;
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(SettingsActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage(content);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                if (nowAppTheme == AdvertUtils.UI_Simple_Mode){
                    LangPublishActivity.uploadError(CustomApplication.loginModel.getNickname()+"切换到了个性模式");
                }else {
                    LangPublishActivity.uploadError(CustomApplication.loginModel.getNickname()+"切换到了标准模式");
                }

                SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.UIModeKey, nowAppTheme);
                //重启
                restartApplication();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void restartApplication() {

        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);

    }


    private void showUnBind(String type){
        String title = "是否要解绑微信？";
        if (type.equals("1")){
            title = "是否要解绑QQ？";
        }
        final CustomDialog.Builder builder = new CustomDialog.Builder(SettingsActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage(title);
        builder.setPositiveButton("解绑", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                avi.show();
                final Map<String, String> map = new HashMap<String, String>();
                map.put("token", CustomApplication.loginModel.getToken());
                map.put("type", type);
                HttpsUtils.miniAppDo(map, "api/user/unbind.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        avi.hide();
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            ToastUtil.show(SettingsActivity.this, "解绑成功");
                            if (type.equals("0")){
                                bindInfoModel.setWx("");
                            }else if (type.equals("1")){
                                bindInfoModel.setQq("");
                            }
                            adapter.notifyDataSetChanged();
                        }else {
                            ToastUtil.show(SettingsActivity.this, commonModel.getMsg());
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        avi.hide();
                    }
                });
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        CustomDialog dialog = builder.create();
        dialog.show();
    }

    private void goUrl(){

        startActivity(new Intent(SettingsActivity.this, WebActivity.class));

    }

    private void logout(){
        /*
        final CustomProgressDialog dialog = new CustomProgressDialog(this, "正在退出登录...",R.anim.frame);
        dialog.setmLoadingTip("正在退出登录...");
        dialog.show();
        */

        if (isLogout == true){
            return;
        }
        isLogout = true;
        avi.setVisibility(View.VISIBLE);
        avi.show();
        final Map<String, String> map = new HashMap<>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.logoutDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                //dialog.dismiss();

                avi.hide();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                CustomApplication.isSign = false;
                CustomApplication.loginModel.setToken(null);
                LogindbService.deleteLoginModel();
                if(commonModel.getFlag().equals("1")){//退出登录成功
                    Intent mIntent = new Intent(BroadcastDefine.Logout_Success_Action);
                    //发送广播
                    sendBroadcast(mIntent);
                    setResult(RESULT_OK);
                    finish();
                }else {
                    Intent mIntent = new Intent(BroadcastDefine.Logout_Success_Action);
                    //发送广播
                    sendBroadcast(mIntent);
                    setResult(RESULT_OK);
                    finish();
                }


            }

            @Override
            public void onError(String msg) {
                //dialog.dismiss();
                isLogout = false;
                avi.hide();
                ToastUtil.show(SettingsActivity.this,"亲，请检查网络连接是否正常");
            }
        });
    }

    private void getUpdate(){
//        final CustomProgressDialog dialog = new CustomProgressDialog(this, "正在检测...",R.anim.frame);
//        dialog.setmLoadingTip("正在检测...");
//        dialog.show();
        PermissionUtils.isPictureNote(SettingsActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                        if (ContextCompat.checkSelfPermission(SettingsActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                            ActivityCompat.requestPermissions(SettingsActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                    MainActivity.REQUEST_PERMISSION);
                            return;
                        }
                    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                            && ContextCompat.checkSelfPermission(SettingsActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(SettingsActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                REQUEST_PERMISSION);
                        //ToastUtil.show(SettingsActivity.this,"亲，请开启应用对SD卡的读写权限");
                        return;
                    }

                    //先检测权限
                    boolean haveInstallPermission;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0
                        //先获取是否有安装未知来源应用的权限
                        haveInstallPermission = getPackageManager().canRequestPackageInstalls();
                        if (!haveInstallPermission) {//没有权限
                            AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
                            builder.setTitle("安装应用需要打开未知来源权限，请去设置中开启权限");
                            builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                        startInstallPermissionSettingActivity();
                                    }
                                }
                            });
                            builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });
                            builder.create().show();
                            return;
                        }
                    }

                    avi.show();
                    final Map<String,String> map = new HashMap<>();
                    map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
                    HttpsUtils.getapkDo(map, new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            //dialog.dismiss();
                            avi.hide();
                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (commonModel.getFlag().equals("1")){
                                apkModel = GsonTools.getApkModel(data);
                                Log.e("更新数据：",data+"\n");
                                if (apkModel != null){
                                    if (apkModel.getVersion().equals(version)){//当前已经是最新版本
                                        ToastUtil.show(SettingsActivity.this,"当前已经是最新版本");
                                    }else {
                                        Message msg = new Message();
                                        msg.what = UPDATA_CLIENT;
                                        handler.sendMessage(msg);
//                            //待处理
//                            new AlertView("温馨提示", "检测到新的版本，是否要更新？", null, new String[]{"立即更新","稍后再说"}, null, SettingsActivity.this, AlertView.Style.Alert, new OnItemClickListener() {
//                    @Override
//                    public void onItemClick(Object o, int position) {
//                         if (position == 0){//立即更新
//                             if (!CommonUtils.isEmpty(apkModel.getApk())){
//                                 download(apkModel.getApk());
//                                 ToastUtil.show(SettingsActivity.this,"正在更新安装包，请稍后");
//                             }
//                         }
//                    }
//                }).show();
                                    }
                                }
                            }else {
                                CustomApplication.showTip(commonModel,SettingsActivity.this);
                            }
                        }

                        @Override
                        public void onError(String msg) {
                            //dialog.dismiss();
                            avi.hide();
                        }
                    });
                }
            }
        });
    }

    private String getVersionName()
    {
        try {
            /*
            // 获取packagemanager的实例
            PackageManager packageManager = getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
            String version = packInfo.versionName;
            */
            return "V"+BuildConfig.VERSION_NAME;
        }catch (Exception e){
            return "";
        }
    }

    private void showDownloadSetting() {
        String packageName = "com.android.providers.downloads";
        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + packageName));
        if (intentAvailable(intent)) {
            startActivity(intent);
        }
    }

    private boolean intentAvailable(Intent intent) {
        PackageManager packageManager = getPackageManager();
        List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }


    private boolean canDownloadState() {
        try {
            int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public void download(String url) {
        if (!canDownloadState()) {
            Toast.makeText(this, "下载服务还没有开启,请你启用", Toast.LENGTH_SHORT).show();
            showDownloadSetting();
            return;
        }
        ApkUpdateUtils.download(this, url, getResources().getString(R.string.app_name));
    }

    //以下是2016-12-31的更新方法
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if (msg == null){
                return;
            }
            switch (msg.what) {
                case UPDATA_NONEED:
                    Toast.makeText(getApplicationContext(), "不需要更新",
                            Toast.LENGTH_SHORT).show();
                case UPDATA_CLIENT:
                    //对话框通知用户升级程序
                    showUpdataDialog();
                    break;
                case GET_UNDATAINFO_ERROR:
                    //服务器超时
                    Toast.makeText(getApplicationContext(), "获取服务器更新信息失败", Toast.LENGTH_SHORT).show();
                    break;
                case DOWN_ERROR:
                    //下载apk失败
                    Toast.makeText(getApplicationContext(), "下载新版本失败", Toast.LENGTH_SHORT).show();
                    break;
                case DOWN_OK:
                    installProcess(apkFile);
                    break;
            }
        }
    };
    /*
     *
     * 弹出对话框通知用户更新程序
     *
     * 弹出对话框的步骤：
     *  1.创建alertDialog的builder.
     *  2.要给builder设置属性, 对话框的内容,样式,按钮
     *  3.通过builder 创建一个对话框
     *  4.对话框show()出来
     */
    protected void showUpdataDialog() {
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(SettingsActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("发现新版本，是否现在升级");
        builder.setPositiveButton("升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                downLoadApk(apkModel.getApk());
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }
    /*
	 * 从服务器中下载APK
	 */
    protected void downLoadApk(final String url) {
        final ProgressDialog pd;    //进度条对话框
        pd = new  ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("下载完成后将会自动提示你更新");
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    File file = DownLoadManager.getFileFromServer(url, pd);
                    sleep(3000);
                    apkFile = file;
                    pd.dismiss(); //结束掉进度条对话框
                    Message msg = new Message();
                    msg.what = DOWN_OK;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = DOWN_ERROR;
                    handler.sendMessage(msg);
                    StringBuffer err = new StringBuffer();
                    StackTraceElement[] stack = e.getStackTrace();
                    for (int i = 0; i < stack.length; i++) {
                        err.append("\tat ");
                        err.append(stack[i].toString());
                        err.append("\n");
                    }
                    //Log.e("TAG", err.toString());
                    LangPublishActivity.uploadError("捕获到了全局异常栈信息："+CommonUtils.formatString(err.toString()));
                    LangPublishActivity.uploadError("捕获到了全局异常："+CommonUtils.formatString(e.getMessage()));
                }
            }}.start();
    }


//安装应用的流程
private void installProcess(File apk) {
    boolean haveInstallPermission;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0
        //先获取是否有安装未知来源应用的权限
        haveInstallPermission = getPackageManager().canRequestPackageInstalls();
        if (!haveInstallPermission) {//没有权限
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("安装应用需要打开未知来源权限，请去设置中开启权限");
            builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        startInstallPermissionSettingActivity();
                    }
                }
            });
            builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.create().show();
            return;
        }
    }
    //有权限，开始安装应用程序
    installApk(apk);
}

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, 10086);
    }

    //安装应用
    private void installApk(File apk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive");
        } else {//Android7.0之后获取uri要用contentProvider
            //Uri uri = FileProvider.getUriForFile(CustomApplication.mContext, CustomApplication.mContext.getPackageName(), apk);//AppCommonUtils.getUriFromFile(getBaseContext(), apk);
            Uri uri = getUriFromFile(getBaseContext(), apk);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //兼容8.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = this.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    ToastUtil.show(SettingsActivity.this,"安装app需要你勾选允许安装未知应用权限");
                    startInstallPermissionSettingActivity();
                    return;
                }
            }
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getBaseContext().startActivity(intent);

    }

    public static Uri getUriFromFile(Context context, File file) {
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context,
                    "com.zhongshengnetwork.rightbe.fileprovider", file);//通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.print("活动返回：onActivityResult\n");
        if (resultCode == RESULT_OK){
            if (requestCode == Register_Request){
                String mobile = data.getExtras().getString("mobile");
                oldMobile = mobile;
                bindInfoModel.setMobile(getMobile(mobile));
                adapter.notifyDataSetChanged();
            }else if (requestCode == Verify_Request){
                String passport = data.getExtras().getString("passport");
                Intent intent = new Intent(SettingsActivity.this, BDThirdActivity.class);
                intent.putExtra("noshow", true);
                intent.putExtra("passport", passport);
                startActivityForResult(intent, Register_Request);
            }else if (requestCode == 10086){
                if (apkFile != null){
                    installProcess(apkFile);
                }
            }
        }
        if(requestCode == Constants.REQUEST_LOGIN){//qq登陆相关
            Tencent.onActivityResultData(requestCode,resultCode,data,mIUiListener);
        }
    }

    //发起微信登陆
    private void wxLogin(){
        avi.show();
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        CustomApplication.mWxApi.sendReq(req);
    }

    /**
     * 广播接收者
     * @author Gordon
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BroadcastDefine.WX_Login)) {
                int result = intent.getIntExtra("errCode",-1);
                if (result == 0){
                    //getToken(intent.getStringExtra(APIKey.codeKey));
                    //wxLoginDo(intent.getStringExtra(APIKey.codeKey));
                    bindwx(intent.getStringExtra(APIKey.codeKey));
                }else{
                    avi.hide();
                    //Toast.makeText(SettingsActivity.this,"登陆失败",Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    /**
     * 注册广播
     * @author Gordon
     */
    public void registerBoradcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        //添加接收广播类型
        myIntentFilter.addAction(BroadcastDefine.WX_Login);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    //获取绑定信息
    private void getbindInfo(){
        final Map<String, String> map = new HashMap<>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.getbindDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    bindInfoModel = GsonTools.getBindInfoModel(data);
                    if (!CommonUtils.isEmpty(bindInfoModel.getMobile())){
                        oldMobile = bindInfoModel.getMobile();
                        bindInfoModel.setMobile(getMobile(bindInfoModel.getMobile()));
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    //注销账号
    private void userOff(){
        avi.setVisibility(View.VISIBLE);
        final Map<String, String> map = new HashMap<>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.userOffDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.setVisibility(View.INVISIBLE);
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    Intent mIntent = new Intent(BroadcastDefine.Logout_Success_Action);
                    //发送广播
                    sendBroadcast(mIntent);
                    setResult(RESULT_OK);
                    finish();
                }
            }

            @Override
            public void onError(String msg) {
                 avi.setVisibility(View.INVISIBLE);
            }
        });
    }

    //设置个性推荐
    private void setPersonalized(){
        int setState = 0;
        if (bindInfoModel == null || CommonUtils.isEmpty(bindInfoModel.getPersonalized()) || bindInfoModel.getPersonalized().equals("1")){
            setState = 0;
        }else {
            setState = 1;
        }
        final Map<String, String> map = new HashMap<>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("state", setState+"");
        HttpsUtils.setPersonalizedDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    if (bindInfoModel == null || CommonUtils.isEmpty(bindInfoModel.getPersonalized()) || bindInfoModel.getPersonalized().equals("1")){
                        bindInfoModel.setPersonalized("0");
                    }else {
                        bindInfoModel.setPersonalized("1");
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    //获取通知设置
    private void getPushState(){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        String url = "miniapp/"+"langappid"+"/getPushState.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    isNotify = GsonTools.getPushState(data);
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.NewMsgTipKey, isNotify);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    //设置通知
    private void setPushState(boolean state){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("state", state+"");
        String url = "miniapp/"+"langappid"+"/setPushState.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {

            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    private String getMobile(String mobile){
        String str = "";
        for (int i = 0; i < mobile.length(); i++) {
            if (i == mobile.length()-11) {
                str += mobile.charAt(i);
            } else if(i == mobile.length()-10) {
                str += mobile.charAt(i);
            }else if(i == mobile.length()-9) {
                str += mobile.charAt(i);
            }else if(i == mobile.length()-3) {
                str += mobile.charAt(i);
            }else if(i == mobile.length()-2) {
                str += mobile.charAt(i);
            }else if(i == mobile.length()-1) {
                str += mobile.charAt(i);
            }else {
                str += "*";
            }
        }
        return str;
    }

    //绑定微信
    private void bindwx(String code){
        final Map<String, String> map = new HashMap<>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put(APIKey.typeKey,"1");
        map.put(APIKey.codeKey,code);
        map.put("flag","1");
        HttpsUtils.bindaccountDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    ToastUtil.show(SettingsActivity.this,"绑定成功");
                    bindInfoModel.setWx("1");
                    adapter.notifyDataSetChanged();
                }else {
                    ToastUtil.show(SettingsActivity.this,commonModel.getMsg());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    //绑定QQ
    private void bindqq(String id, String nickname){
        final Map<String, String> map = new HashMap<>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put(APIKey.typeKey,"2");
        map.put(APIKey.idKey,id);
        map.put("flag","1");
        map.put("nickname",nickname);
        HttpsUtils.bindaccountDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    ToastUtil.show(SettingsActivity.this,"绑定成功");
                    bindInfoModel.setQq("1");
                    adapter.notifyDataSetChanged();
                }else {
                    ToastUtil.show(SettingsActivity.this,commonModel.getMsg());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    //绑定手机
    private void bindMobile(){
        Intent intent = new Intent(SettingsActivity.this,BDThirdActivity.class);
        intent.putExtra("noshow", true);
        startActivityForResult(intent,Register_Request);
    }

    //更换手机
    private void changeMobile(){
        List<String> moreList = new ArrayList<String>();
        moreList.add("通过验证码更换手机");
        moreList.add("通过登录密码更换手机");
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(SettingsActivity.this)
                .builder()
                .setTitle("更改手机号")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : moreList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        Intent intent = new Intent(SettingsActivity.this, VerifyActivity.class);
                        intent.putExtra("type", which-1);
                        intent.putExtra("mobile", oldMobile);
                        startActivityForResult(intent, Verify_Request);
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    //以下是qq相关
    /**
     * 自定义监听器实现IUiListener接口后，需要实现的3个方法
     * onComplete完成 onError错误 onCancel取消
     */
    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            Log.e("TAG", "response:" + response);
            JSONObject obj = (JSONObject) response;
            try {
                final String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken,expires);
                QQToken qqToken = mTencent.getQQToken();
                mUserInfo = new UserInfo(getApplicationContext(),qqToken);
                mUserInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response) {
                        Log.e("TAG","登录成功"+response.toString());
                        final JSONObject jo = (JSONObject) response;
                        try {
                           bindqq(openID,jo.getString("nickname"));
                        }catch (Exception e){

                        }
                    }

                    @Override
                    public void onError(UiError uiError) {
                        avi.hide();
                        Log.e("TAG","登录失败"+uiError.toString());
                    }

                    @Override
                    public void onCancel() {
                        avi.hide();
                        Log.e("TAG","登录取消");

                    }

                    @Override
                    public void onWarning(int i) {

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            avi.hide();
            Toast.makeText(SettingsActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
            avi.hide();
            Toast.makeText(SettingsActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onWarning(int i) {

        }

    }


}
